<script setup lang="ts">
import {CopyOutlined, DeleteOutlined, PlusOutlined} from "@ant-design/icons-vue";
import {message} from "ant-design-vue";
import ClipboardJS from "clipboard";

const emit = defineEmits([])
const props = defineProps({
  tabKey: {
    type: String,
    default: 'relatedWord'
  },
  data: {
    type: Array,
    default: () => [],
  },
  columns: {
    type: Array,
    default: () => [],
  },
})
const keywords = ref([]);
const maxNum = ref(0);
const calcBgColor = (word: any) => {
  let num1 = 0;
  for (let i = 0; i < props.data.length; i++) {
    if (props.data[i].keyword.toLowerCase().includes(word.toLowerCase())) {
      if (parseFloat(props.data[i][choseDataIndex.value]) > num1) {
        num1 = parseFloat(props.data[i][choseDataIndex.value]);
      }
    }
  }
  //计算颜色 按照百分比 从#fff到#00f 从白色到蓝色分为10个阶段
  let color = '#fff';
  if (maxNum.value === 0) {
    color = '#00f';
  }
  console.log(num1, maxNum.value);
  if (num1 > 0 && maxNum.value > 0) {
    let percent = num1 / maxNum.value;
    let step = Math.floor(percent * 10);
    if (step < 2) {
      step = 2;
    }
    let r = 255 - step * 25;
    let g = 255 - step * 25;
    let b = 255;
    color = `rgb(${r},${g},${b})`;
  }
  if (!num1) {
    color = '#aaa';
  }
  return color;
}
const tableData = ref<any[]>([]);
const tableColumns = ref([
  {
    dataIndex: 'title',
    title: '标题',
    width: 160,
    tooltip: true,
    fixed: 'left',
  },
  {
    dataIndex: 'wordNumber',
    title: '词数',
    width: 60,
    align: 'right',
    fixed: 'left',
  },
  ...props.columns?.filter((column: any) => typeof column.calc !== 'undefined' && column.calc),
]);
const keyword = ref('')
const visible = ref(false)
const choseDataIndex = ref('seIpvUvHits_tran');
const calcTableData = () => {
  let title = keywords.value.join('');
  let wordNumber = keywords.value.length;
  let indexes = props.columns?.filter((column: any) => typeof column.calc !== 'undefined' && column.calc).map((column: any) => column.dataIndex);
  let data: any =
      {
        title,
        wordNumber,
        ...indexes.map((index) => {
          return {
            [index]: calcData(index),
          };
        }),
      };
  for (const dataKey in data) {
    if (data.hasOwnProperty(dataKey)) {
      const dataValue = data[dataKey];
      if (typeof dataValue === 'object') {
        let obj = {...dataValue};
        delete data[dataKey];
        data = {
          ...data,
          ...obj,
        }
      }
    }
  }
  console.log(data);
  tableData.value = [];
  tableData.value.push(data);
}
const calcData = (index: string) => {
  let nums: Array<number> = [];
  keywords.value.forEach((word) => {
    let max = 0;
    for (let i = 0; i < props.data.length; i++) {
      if (props.data[i].keyword.toLowerCase().includes(word.toLowerCase())) {
        if (parseFloat(props.data[i][index]) > max) {
          max = parseFloat(props.data[i][index]);
        }
      }
    }
    nums.push(max);
  });
  // nums平均数
  let num = 0;
  nums.forEach((n) => {
    num += n;
  });
  if (nums.length === 0) {
    return 0;
  }
  num = num / nums.length;
  return parseFloat(num.toFixed(2));
}
onMounted(() => {
  let clipboard = new ClipboardJS('.copyBtn');
  clipboard.on('success', function (e) {
    message.success('复制成功!');
    e.clearSelection();
  });
  maxNumCalc();
})
const maxNumCalc = () => {
  let max = 0;
  props.data.forEach((item: any) => {
    if (parseFloat(item[choseDataIndex.value]) > max) {
      max = parseFloat(item[choseDataIndex.value]);
    }
  });
  maxNum.value = max;
}
watch(() => props.data, () => {
  maxNumCalc();
}, {
  deep: true
})
watch(() => choseDataIndex.value, () => {
  maxNumCalc();
})
const onOrderChange = (event: any) => {
  // keywords.value下 oldIndex 和 newIndex 数据颠倒位置
  let oldIndex = event.oldIndex;
  let newIndex = event.newIndex;
  let temp = keywords.value[oldIndex];
  keywords.value[oldIndex] = keywords.value[newIndex];
  keywords.value[newIndex] = temp;
  let keys = [...keywords.value];
  keywords.value = [];
  nextTick(() => {
    keywords.value = keys;
  });
}
watch(() => keywords.value, () => {
  calcTableData();
}, {
  deep: true
})
const deleteKey = (index: number) => {
  keywords.value.splice(index, 1);
  let keyDatas = [...keywords.value];
  keywords.value = [];
  nextTick(() => {
    keywords.value = keyDatas;
  });
}
</script>

<template>
  <base-table :columns="tableColumns" style="margin-bottom: 10px;" :data-source="tableData" size="small"
              table-name="标题生成优化数据"
              v-if="keywords.length>0"
  >

  </base-table>
  <div class="generation_box">
    <a-row type="flex" class="title">
      <a-col>当前标题</a-col>
      <a-col flex="1">
        <a-row type="flex">
          <a-col flex="1" style="padding-left: 20px;color: #444;">
            {{ keywords.join('') }}
          </a-col>
          <a-col>
            <a-popover trigger="click" v-model:open="visible" placement="bottom">
              <template #content>
                <a-input-search
                    v-model:value="keyword"
                    placeholder="请输入关键词"
                    size="small"
                    @search="()=>{
                      keywords.push(keyword);
                  visible=false;
                  keyword='';
                }"
                >
                  <template #enterButton>
                    <a-button size="small" type="primary">添加</a-button>
                  </template>
                </a-input-search>
              </template>
              <a-button type="link" size="small" style="font-size: 14px;">
                <PlusOutlined/>
                添加关键词
              </a-button>
            </a-popover>

            <a-button type="link" size="small" style="color: #ff4d4f;font-size: 14px;"
                      @click="keywords.clear()"
            >
              <DeleteOutlined/>
              清空关键词
            </a-button>

            <a-button type="link" size="small" style="font-size: 14px;" :data-clipboard-text="keywords.join('')"
                      class="copyBtn"
            >
              <CopyOutlined/>
              复制标题
            </a-button>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
    <div style="padding: 10px;">
      <a-row type="flex" class="notice">
        <a-col>
          <a-select placeholder="选择参考标准" v-model:value="choseDataIndex" size="small"
                    style="width: 160px;margin-right: 10px;"
          >
            <a-select-option
                v-for="(option) in columns.filter((column)=>typeof column.calc!=='undefined' && column.calc)"
                :value="option.dataIndex"
            >
              {{ option.title }}
            </a-select-option>
          </a-select>
          <div class="color-example-box"> 颜色越深表示数值越高</div>

          <div class="color-none"> 表示无指标数值</div>
        </a-col>
        <a-col flex="1">
        </a-col>
      </a-row>
      <div style="padding: 10px 0;" v-sortable @end="onOrderChange">
        <a-tag v-for="(word,index) in keywords" :color="calcBgColor(word)" :key="index" closable @close="deleteKey(index)"
        >
          {{ word }}
        </a-tag>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.generation_box {
  border: 1px solid #eee;
  // 圆角
  border-radius: 5px;
  overflow: hidden;
  margin-top: 10px;
  &:hover {
    // 加阴影
    box-shadow: 0 0 10px #eee;
  }

  .title {
    padding: 7px 10px;
    background: #fff8f2;
    font-size: 14px;
    font-weight: bold;
  }

  .notice {
    background: #f4f4f5;
    display: flex;
    padding: 10px;
    font-size: 14px;
  }

  .color-example-box {
    display: inline-block;
    font-size: 14px;
    color: #444;

    &:before {
      content: '';
      display: inline-block;
      width: 50px;
      height: 14px;
      border-radius: 2px;
      background: linear-gradient(90deg, #fff, #00f);
      vertical-align: middle;
    }
  }

  .color-none {
    display: inline-block;
    margin-left: 20px;
    font-size: 14px;
    color: #444;

    &:before {
      content: '';
      display: inline-block;
      width: 14px;
      height: 14px;
      border-radius: 2px;
      background: #aaa;
      vertical-align: middle;
    }
  }
}
</style>
